package com.yindian.cos.easy.security.authentication.login.social.qq;

import com.yindian.cos.easy.security.authentication.login.social.core.AbstractSocialAuthentication;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.QqProperties;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * qq登录拦截器
 *
 * @author zhangchuanhao
 * @create 2018/11/19
 */
@Log4j2
public class QqLoginAuthentication extends AbstractSocialAuthentication {

    private final QqProperties qqProperties;

    private final String loginUrl;

    private final String method;

    public QqLoginAuthentication(EasySecurityProperties easySecurityProperties) {
        this.qqProperties = easySecurityProperties.getQq();
        this.loginUrl = qqProperties.getLoginUrl();
        this.method = qqProperties.getMethod();
    }

    @Override
    public boolean support(HttpServletRequest request) {
        return support(request, method, loginUrl);
    }

    @Override
    public int order() {
        return qqProperties.getOrder();
    }

    @Override
    public void redirectAuthorization(HttpServletResponse response) throws IOException {
        String url = qqProperties.getAuthorizationCodeUrl();
        url += "?response_type=" + qqProperties.getResponseType();
        url += "&client_id=" + qqProperties.getAppId();
        url += "&redirect_uri=" + URLEncoder.encode(qqProperties.getDomain() + qqProperties.getRedirectUri(), "utf-8");
        url += "&state=" + qqProperties.getState();
        if (StringUtils.isNotBlank(qqProperties.getScope())) {
            url += "&scope=" + qqProperties.getScope();
        }
        if (StringUtils.isNotBlank(qqProperties.getDisplay())) {
            url += "&display=" + qqProperties.getDisplay();
        }
        response.sendRedirect(url);
        log.debug(ProviderName.QQ + "登录引导用户跳转至授权页面...");
    }
}
